import axios from "axios";

export class Config {
    /**
     * that 用于处理error弹窗 this
     *
     * */
    static async getOptions(fieldName, that) {
        let result = [];
        try {
            let url = "/hr/api/setting/getOptions"
            let data = {"fieldName": fieldName}
            let response = await this.getData(url, data)
            if (!response.data.success) {
                that.$notify({
                    message: response.data.errMessage,
                    type: 'warning'
                });
                result = []
            } else {
                result = response.data.data
            }

        } catch (err) {
            that.$notify({
                message: err,
                type: 'warning'
            });
        }
        return result;

    }

    static postDatas(url, data = {}, fn, that, errs = () => {
    }) {
        axios.post(url, data).then(res => {
            if (res.data.success) {
                fn(res.data.data);
            } else {
                throw res.data.errMessage;
            }
        }).catch(err => {
            errs()
            that.$toast({
                message: err,
                type: 'warning'
            });
        })

    }

    static download(url, data = {}, fn, that, errs = () => {
    }) {
        axios({
            url: url,
            method: 'post',
            headers: {
                'Content-type': 'application/x-www-form-urlencoded'
            },
            data: data,
            responseType: 'blob'
        }).then(res => {
            fn(res);
        }).catch(err => {
            errs()
            that.$notify({
                message: err,
                type: 'warning'
            });
        })
    }

    static downloadWithFileName(url, fileName, data = {}, that, errs = () => {
    }) {
        Config.download(url, data, res => {
            let a = document.createElement('a');
            a.download = fileName;
            a.href = window.URL.createObjectURL(new Blob([res.data]));
            a.click();
        }, that, errs())
    }

    static getDatas(url, data = {}, fn, that, errs = () => {
    }) {
        axios.get(url, {
            params: data
        }).then(res => {
            if (res.data.success) {
                fn(res.data.data);
            } else {
                throw res.data.errMessage;
            }
        }).catch(err => {
            errs(err)
            that.$toast({
                message: err,
                type: 'warning'
            });
        })
    }

    static getData(url, data = {}) {
        return axios.get(url, {
            params: data
        });
    }

    static postData(url, data = {}) {
        return axios.post(url, data);
    }
}
